package com.b511.swpu.cementbackend.exception;

import com.b511.swpu.cementbackend.util.enumeration.Code;
import com.b511.swpu.cementbackend.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@ControllerAdvice
@ResponseBody
public class ExceptionHandler {
    @org.springframework.web.bind.annotation.ExceptionHandler(value = CementException.class)
    public R handlerCementException(CementException e) {
        Code code = e.getCode();
        return R.error(code.getCode(), code.getMsg());
    }

    @org.springframework.web.bind.annotation.ExceptionHandler(MethodArgumentNotValidException.class)
    public R bindException(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        List<String> errors = fieldErrors.stream().map(FieldError::getDefaultMessage).collect(Collectors.toList());
        R result = R.error();
        result.put("errors", errors);
        return result;
    }

    @org.springframework.web.bind.annotation.ExceptionHandler(value = Exception.class)
    public R handlerException(Exception e) {
        log.error(e.getMessage());
        System.out.println(e.getMessage());
        return R.error("哇喔，系统崩溃了。请尽快联系管理员！");
    }
}
